﻿using System;

namespace JSH.ITDiplom.OOPC01.PersonalIdentityNumber.BusinessLayer.se
{
    /// <summary>
    /// Swedish checksum validation.
    /// </summary>
    class ChecksumValidation : IPersonalIdentityNumberValidation
    {
        private readonly string personalIdentityNumber;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="personalIdentityNumber">Personal identity number</param>
        public ChecksumValidation(string personalIdentityNumber)
        {
            this.personalIdentityNumber = personalIdentityNumber;
        }

        /// <summary>
        /// Validate.
        /// </summary>
        /// <returns>Returns true if personal identity number is valid.</returns>
        public bool Validate()
        {
            try
            {
                int checksum = Sum(personalIdentityNumber);
                if (checksum == Int32.Parse(personalIdentityNumber.Substring(10, 1)))
                {
                    return true;
                }
            }
// ReSharper disable EmptyGeneralCatchClause
            catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
            {}
            return false;
        }

        private static int Sum(string str)
        {
            int sum = 0;
            for (int i = 0; i < 10; i++)
            {
                switch (i)
                {
                    case 0:
                    case 2:
                    case 4:
                    case 7:
                    case 9:
                        int temp = 2 * Int32.Parse(str.Substring(i, 1));
                        if (temp > 9) temp = 1 + (temp - 10);
                        sum += temp;
                        break;
                    case 6: //Ignore dash
                        break;
                    default:
                        sum += Int32.Parse(str.Substring(i, 1));
                        break;
                }
            }
            int checksum = 10 - (sum % 10);
            if (checksum == 10) checksum = 0;
            return checksum;
        }

        /// <summary>
        /// Calculate checksum
        /// </summary>
        /// <param name="first10Chars">First 10 char. of personal identify number.</param>
        /// <returns>Checksum value</returns>
        public static int Calculate(string first10Chars)
        {
            return Sum(first10Chars);
        }
    }
}